-- UISkillOperation
-- Create by luohj Jan/29/2015
-- 技能操作界面

UISkillOperation = class("UISkillOperation",function()
    return cc.Layer:create();
end
);

function UISkillOperation.create(skillId, isLictor, heroId, isEnough)
    return UISkillOperation.new(skillId, isLictor, heroId, isEnough);
end

-- 背景框切片数量
local SMALL_BG_COUNT = 4;

-- 构造函数
function UISkillOperation:ctor(skillId, isLictor, heroId, isEnough)
    -- 初始化
    self:setName("UISkillOperation");
    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    local node = cc.CSLoader:createNode("layout/hero/SkillOperate.csb");
    self:addChild(node);
    self.node = node;
    local CT = node:getChildByName("CT");

    self.skillId = skillId;
    self.islictor = isLictor;
    self.heroId = heroId;
    self.isEnough = isEnough;

    self.CT = CT;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback()

    self:initView();

    -- 适配
    self:resize(node);
end

-- 注册事件处理回调函数
function UISkillOperation:registerEventCallback()
    -- 注册英雄佩戴技能的回调
    EventMgr.register("UISkillOperation", event.SET_SKILL_OPTION, function(args)
        -- 提示玩家重置技能成功
        alert(getLocStr("reset_skill_succ"));
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISkillOperation 界面析构清理");

            EventMgr.remove("UISkillOperation", event.SET_SKILL_OPTION);
        end
    end);
end

function UISkillOperation:initView()
    local btnChangeSkill = findChildByName(self.node, "BT/btn_change_skill");
    btnChangeSkill:setVisible(false);

    -- 设置装备名字
    local nameLabel = findChildByName(self.CT, "name");
    local name = SkillM.query(self.skillId, "name");
    local rank = SkillM.query(self.skillId, "level");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(name.. " Lv.".. rank);

    -- 设置装备效果
    local effectLabel = findChildByName(self.CT, "effect");
    local effect = SkillM.getSkillDesc(self.skillId);

    if self.islictor then
        effect = SkillM.getSkillDesc(self.skillId, true, "lictor");
    end

    if self.isEnough then
        effect = SkillM.getSkillDesc(self.skillId, true, "lictor");
    end

    local hintStr = string.format(getLocStr("feed_pet_hint"))
    TextStyleM.setTextStyle(effectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 一些技能的特殊处理，如果世界树冈布奥、收魂者冈布奥的专属技能需要显示进度
    local specialDesc = "";
    local effectDesc = "";

    local amount;
    local maxValue;

    if self.heroId and DungeonM.isInDungeon() and not DungeonM.isPause() then
        local baseSkillId = SkillM.findBaseSkill(self.skillId);
        if baseSkillId == 731 then
            -- 灵魂收割技能
            amount = ME.user.dbase:query("soul_collect", 0);
            maxValue = PropM.combine(ME.user, "soul_to_revive", 500)[3] or 100;

            local amountStr = iif(amount < maxValue, "[-][red]"..tostring(amount).."[-][blue]", tostring(amount));
            specialDesc = string.format(getLocStr("soul_chip"), amountStr, maxValue);
            effectDesc = effect .. "\n" .. specialDesc .. hintStr;

        elseif baseSkillId == 741 then
            -- 远古之源技能
            amount = ME.user.dbase:query("vital_essence", 0);
            maxValue = PropM.combine(ME.user, "soul_to_item", 7158)[3] or 100;

            local amountStr = iif(amount < maxValue, "[-][red]"..tostring(amount).."[-][blue]", tostring(amount));
            specialDesc = string.format(getLocStr("vital_essence"), amountStr, maxValue);
            effectDesc = effect .. "\n" .. specialDesc  .. hintStr;
        elseif baseSkillId == 841 then
            -- 杀戮程式技能
            amount = ME.user.dbase:query("opti_point", 0);
            maxValue = 100;

            local amountStr = iif(amount < maxValue, "[-][red]"..tostring(amount).."[-][blue]", tostring(amount));
            specialDesc = string.format(getLocStr("opti_point"), amountStr, maxValue);
            effectDesc = effect .. "\n" .. specialDesc  .. hintStr;
        else
            local dungeonAttrib = SkillM.query(baseSkillId, "dbase")["dungeon_attrib"];
            if dungeonAttrib ~= nil then
                local name = DungeonServiceM.getDungeonAttribInfo(dungeonAttrib, "name");
                if type(dungeonAttrib) == 'number' then
                    -- 如果是物品
                    name = ItemM.query(dungeonAttrib, "name");
                    amount = ItemM.getAmount(ME.user, dungeonAttrib);
                    maxValue = 1;
                else
                    amount = DungeonServiceM.queryDungeonAttrib(dungeonAttrib);
                    maxValue = DungeonServiceM.getDungeonAttribInfo(dungeonAttrib, "limit");
                end

                -- 判断是否有至少一个技能满足消耗
                local function isEnough()
                    local skills = SlimeSkillM.getSamePetSkills(self.heroId);
                    for _, skillId in pairs(skills) do
                        local slimeSkillId = SlimeSkillM.getSlimeActiveSkillId(skillId);
                        if SlimeSkillM.enoughtEnergy(slimeSkillId) then
                            return true;
                        end
                    end

                    return false;
                end

                local amountStr = iif(isEnough(), tostring(amount), "[-][red]"..tostring(amount).."[-][blue]");
                specialDesc = string.format(getLocStr("dungeon_attrib_str"), name, amountStr, maxValue);
                effectDesc = effect .. "\n" .. specialDesc  .. hintStr;
           end
        end
    else
        effectDesc = effect .. hintStr;
    end

    effectLabel = applyString(effectLabel, effect .. "\n" .. specialDesc .. hintStr);

    local btnChangeSkill = findChildByName(self.node, "BT/btn_change_skill");
    btnChangeSkill:setVisible(false);

    -- 注册任意地方点击返回事件
    local btnBgBack = findChildByName(self.node, "bg/bgImg");
    local function onBgBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkillOperation");
        end
    end
    btnBgBack:addTouchEventListener(onBgBackClick);

    -- 显示灵魂链接
    local lictorLabel = findChildByName(self.CT, "explain");
    TextStyleM.setTextStyle(lictorLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BLUE);
    local lictorStr = getLocStr("soul_link");
    lictorLabel:setString(lictorStr);
    if self.islictor then
        lictorLabel:setVisible(true);
    end

    local btnSkill1 = findChildByName(self.node, "CT/btn_skill1");
    local btnSkill2 = findChildByName(self.node, "CT/btn_skill2");
    local btns = {btnSkill1, btnSkill2};
    if self.heroId == nil then
        btnSkill1:setVisible(false);
        btnSkill2:setVisible(false);
    else
        -- 当前冈布奥对应的所有主动技
        local skills = SlimeSkillM.getSamePetSkills(self.heroId);
        -- 多个按钮（目前最多2个）
        for i = 1, 2 do
            local btnSkill = btns[i];
            btnSkill:setVisible(#skills >= i);
            if #skills >= i then
                btnSkill.skillId = skills[i];
                local slimeSkillId = SlimeSkillM.getSlimeActiveSkillId(skills[i]);
                setButtonEnabled(btnSkill, SlimeSkillM.enoughtEnergy(slimeSkillId));

                local name = SlimeSkillM.query(slimeSkillId, "name");
                TextStyleM.setTextStyle(btnSkill, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
                btnSkill:setTitleText(name);
            end
        end
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_SMALL, { nameLabel, effectLabel, });

    -- 灵魂链接的纵坐标和名称保持一致
    lictorLabel:setPositionY(nameLabel:getPositionY());
    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_SMALL,
        { nameLabel, effectLabel, btnSkill1, btnSkill2 },
        { AlignM.DEFAULT_GAP, 1.5* AlignM.DEFAULT_GAP, -10 });
end

--适配
function UISkillOperation:resize(node)
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UISkillOperation:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkillOperation");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册任意地方点击返回事件
    local btnBgBack = findChildByName(self.node, "bg/bgImg");
    local function onBgBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkillOperation");
        end
    end
    btnBgBack:addTouchEventListener(onBgBackClick);

    -- 防止点击事件被吞掉
    local bg = findChildByName(self.node, "CT/bg");
    for i = 1, SMALL_BG_COUNT do
        local subBg = findChildByName(bg, "bg" .. i);
        if subBg ~= nil then
            subBg:setSwallowTouches(false);
        end
    end

    -- 技能释放按钮
    local btnSkill1 = findChildByName(self.node, "CT/btn_skill1");
    local function onBtnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 施放技能
            local skillId  = sender.skillId;

            UIMagicScrolls:tryUseSkill(skillId);

            UIMgr.getCurrentScene():removeFormByName("UISkillOperation");
        end
    end
    btnSkill1:addTouchEventListener(onBtnClick);

    local btnSkill2 = findChildByName(self.node, "CT/btn_skill2");
    btnSkill2:addTouchEventListener(onBtnClick);
end
